﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace CPPEI.Coolzon.Tools.INSVideoTool
{
    class LoginClientOnceWithTimeOut : ILoginClientStrategy
    {
        private ManualResetEvent _manualResetEvent = new ManualResetEvent(false);
        private TimeSpan _timeOut;
        private static Dictionary<string, int> _loginInfoList = new Dictionary<string, int>();
        private static string _loginInfoTemplate = "{0}:{1},{2}";
        public LoginClientOnceWithTimeOut(int timeOutSeconds = 5)
        {
            _timeOut = TimeSpan.FromSeconds(timeOutSeconds);
        }
        public int LoginClient(VideoClient.ClientSummary videoclient, string userName, string passWord, string url)
        {
            string _loginInfo = string.Format(_loginInfoTemplate, userName, passWord, url);
            if (_loginInfoList.Keys.Contains(_loginInfo))
            {
                return _loginInfoList[_loginInfo];
            }
            else
            {
                int loginNo = 0;
                new Action(() => { loginNo = videoclient.LoginClient(userName, passWord, url); }).BeginInvoke(delegate { _manualResetEvent.Set(); }, null);
                _manualResetEvent.WaitOne(_timeOut);
                _loginInfoList.Add(_loginInfo, loginNo);
                return loginNo;
            }
        }
        public static void ClearLoginClientInfo()
        {
            if (_loginInfoList.Count > 0)
            {
                _loginInfoList.Clear();
            }
        }
    }
}
